package leetcode.d_1_99;


public class P61 {
    public static void main(String[] args) {
        P61 test = new P61();
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        ListNode node = test.rotateRight(head, 2); // 4,5,1,2,3
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }

        // 连接链表头尾节点
        ListNode tail = head;
        int len = 1;
        while(tail.next != null) {
            tail = tail.next;
            len++;
        }

        k = len- k%len;
        if (k==len) {
            return head;
        }

        tail.next = head;
        // 找到切断的节点
        for(;k>0;k--) {
            tail = tail.next;
        }
        ListNode next = tail.next;
        tail.next = null;
        return next;
    }
}
